package com.zghhost.stockweb.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zghhost.stockweb.constans.WangyiConstans;
import com.zghhost.stockweb.entity.SinaDadanEntity;
import com.zghhost.stockweb.pojo.WangyiYidongBean;
import com.zghhost.stockweb.service.impl.SinaDadanService;
import com.zghhost.stockweb.util.DateUtil;
import com.zghhost.stockweb.util.DayUtil;
import com.zghhost.stockweb.util.HttpUtil;
import com.zghhost.stockweb.util.NumberUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author guohua.zhang@zhaopin.com.cn
 * @Date 2019/5/22 20:37
 */
@Controller
@RequestMapping("yidong")
public class YiDongController {
    @Autowired
    SinaDadanService sinaDadanService;

    @RequestMapping
    public String index(HttpServletRequest req, HttpServletResponse res)throws Exception{
        JSONArray jarr = fetchYiDong();

        List<WangyiYidongBean> yidongs = JSONArray.parseArray(jarr.toString(),WangyiYidongBean.class);
        Map<String,List<WangyiYidongBean>> statis =  yidongs.stream().collect(Collectors.groupingBy(
                WangyiYidongBean::getCODE
            )
        );

        Map<WangyiYidongBean,List<WangyiYidongBean>> resstatis = new HashMap<>();
        statis.keySet().stream().forEach(key -> {
            List<WangyiYidongBean> es = statis.get(key);

            WangyiYidongBean newe = new WangyiYidongBean();
            newe.setStaamount(0D);
            es.stream().forEach(e -> {
                newe.setCODE(e.getCODE());
                newe.setNAME(e.getNAME());
                if(newe.getDATE() == null){
                    newe.setDATE(e.getDATE());
                }
                if(e.getTYPE().indexOf("卖") != -1){
                    newe.setStaamount(newe.getStaamount()+(0-e.getAMOUNT()));
                }else{
                    newe.setStaamount(newe.getStaamount()+e.getAMOUNT());
                }
            });

            resstatis.put(newe,es);
        });

        Map<WangyiYidongBean,List<WangyiYidongBean>> filteredData = resstatis.entrySet().stream().filter(e -> Math.abs(e.getKey().getStaamount().longValue()) > 500000).collect(Collectors.toMap(e->e.getKey(),e->e.getValue()));

        StringBuffer codes = new StringBuffer();
        for(WangyiYidongBean key : filteredData.keySet()){
            if(codes.length()>0){
                codes.append(",");
            }
            codes.append(key.getCODE());
        }

        try{
            JSONObject priceDict = fetchCurrentPrice(codes.toString());
            if(priceDict != null){
                filteredData.keySet().stream().forEach(key -> {
                    JSONObject priceJobj = priceDict.getJSONObject(key.getCODE());
                    if(priceJobj != null){
                        key.setCurrentPrice(priceJobj.getString("price"));
                        key.setUpdownRate(priceJobj.getString("updown"));
                    }
                });
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        Map<WangyiYidongBean,List<WangyiYidongBean>> resstatisSorted = new TreeMap<>(new Comparator<WangyiYidongBean>() {
            @Override
            public int compare(WangyiYidongBean o1, WangyiYidongBean o2) {
                return o2.getStaamount().compareTo(o1.getStaamount());
            }
        });
        resstatisSorted.putAll(filteredData);

        req.setAttribute("values",resstatisSorted);
        return "yidong";
    }

    public JSONArray fetchYiDong()throws Exception{
        String resdata = HttpUtil.doHttpGet(WangyiConstans.WANGYI_YIDONG_URL,"utf-8");
        resdata = resdata.substring(resdata.indexOf("(")+1,resdata.length()-1);
        JSONObject job = JSONObject.parseObject(resdata);
        JSONArray jarr = job.getJSONArray("list");
        return jarr;
    }

    public JSONObject fetchCurrentPrice(String cdeosStr)throws Exception{
        String resdata = HttpUtil.doHttpGet(String.format(WangyiConstans.CURRENT_PRICE_URL,cdeosStr),"utf-8");
        resdata = resdata.substring(resdata.indexOf("(")+1,resdata.length()-2);
        return JSONObject.parseObject(resdata);
    }

    @RequestMapping("dadan")
    @ResponseBody
    public Object getSinaDaDan(@RequestParam(required = true) String code)throws Exception{
        if(code.length() == 7){
            code = code.substring(1);
        }

        if(code.startsWith("6")){
            code = "sh"+code;
        }else{
            code = "sz" + code;
        }

        Date[] days = DayUtil.dayWithoutWeekday(5);

        String sday,eday;
        eday = DateUtil.parseDateToStr(days[0],DateUtil.DATE_FORMAT_YYYY_MM_DD);
        sday = DateUtil.parseDateToStr(days[days.length-1],DateUtil.DATE_FORMAT_YYYY_MM_DD);

        List<SinaDadanEntity> daysData = sinaDadanService.getDayRangeDadan(code, sday, eday);

        Map<String,List<SinaDadanEntity>> dayGroupData = daysData.stream().collect(Collectors.groupingBy(SinaDadanEntity::getDay));
        Map<String,List<SinaDadanEntity>> sortedDayGroupData = new TreeMap<>(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                Date o1d = DateUtil.parseStrToDate(o1,DateUtil.DATE_FORMAT_YYYY_MM_DD);
                Date o2d = DateUtil.parseStrToDate(o2,DateUtil.DATE_FORMAT_YYYY_MM_DD);
                return o2d.compareTo(o1d);
            }
        });
        sortedDayGroupData.putAll(dayGroupData);

        StringBuffer sb = new StringBuffer();

        sortedDayGroupData.keySet().stream().forEach(key -> {
            List<SinaDadanEntity> sinaDadanEntities = dayGroupData.get(key);
//
            Map<String, Double[]> map = new HashMap<String, Double[]>();

            for (SinaDadanEntity sinaDadanEntity : sinaDadanEntities) {
                if (map.get(sinaDadanEntity.getKind()) == null) {
                    map.put(sinaDadanEntity.getKind(), new Double[]{0D, 0D, 0D, 0D, 0D});
                }
                map.get(sinaDadanEntity.getKind())[0] = map.get(sinaDadanEntity.getKind())[0] + sinaDadanEntity.getPrice();
                map.get(sinaDadanEntity.getKind())[1] = map.get(sinaDadanEntity.getKind())[1] + sinaDadanEntity.getVolume();
                map.get(sinaDadanEntity.getKind())[2] = map.get(sinaDadanEntity.getKind())[2] + (sinaDadanEntity.getVolume() * sinaDadanEntity.getPrice());
                map.get(sinaDadanEntity.getKind())[4] = map.get(sinaDadanEntity.getKind())[4] + 1;
            }

            Double[] U = map.get("U");
            Double[] D = map.get("D");

            sb.append(key).append("\n<br/>");

            try {
                sb.append("U: " + NumberUtil.formatNum("" + U[1], false) + " " + NumberUtil.formatNum("" + U[2], false) + " " + (U[2] / U[1]) + " " + (U[1] / U[4])).append("\n<br/>");
            }catch (Exception e){}
            try {
                sb.append("D: " + NumberUtil.formatNum(""+D[1],false) + " " + NumberUtil.formatNum("" + D[2], false) + " " + (D[2] / D[1]) + " " + (D[1] / D[4])).append("\n<br/>");
            }catch (Exception e){}

            sb.append("\n<br/>");
        });

        return sb.toString();
    }
}
